package backtracking;

import java.util.*;

/**
 * 47.全排列||
 * 给定一个可包含重复数字的序列 nums ，按任意顺序 返回所有不重复的全排列。
 */
public class permuteUnique {
    /**
     * 一刷二刷思路一致，直接看二刷，思路简洁
     */
    public List<List<Integer>> permuteUnique(int[] nums) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        List<Integer> list = new ArrayList<>();
        Boolean uesd[] = new Boolean[nums.length];
        Arrays.fill(uesd, false);
        Arrays.sort(nums);
        backtrack(nums, res, list, uesd);
        return res;
    }

    public void backtrack(int[] nums, List<List<Integer>> res, List<Integer> list, Boolean[] used) {
        if (list.size() == nums.length) {
            res.add(new ArrayList<>(list));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            if (used[i]) continue;
            if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) continue;
            list.add(nums[i]);
            used[i] = true;
            backtrack(nums, res, list, used);
            used[i] = false;
            list.remove(list.size() - 1);
        }
    }
    /**
     * 二刷
     */
    class Solution {
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> path = new ArrayList<>();
        boolean used[];

        public List<List<Integer>> permuteUnique(int[] nums) {
            used = new boolean[nums.length];
            Arrays.sort(nums);
            backtracking(nums);
            return res;
        }

        public void backtracking(int[] nums) {
            if (path.size() == nums.length) {
                res.add(new ArrayList<>(path));
                return;
            }
            for (int i = 0; i < nums.length; i++) {
                if (used[i]) {
                    continue;
                }
                if (i > 0 && nums[i] == nums[i - 1] && !used[i-1]) {
                    continue;
                }
                path.add(nums[i]);
                used[i] = true;
                backtracking(nums);
                path.removeLast();
                used[i] = false;
            }
        }
    }
}
